import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import { Layout, Spin, Typography, Button, Space } from 'antd';
import { useAuth } from '../authContext/authContext';
import './landing.css'; // 引入自定义样式
import { Header } from 'antd/es/layout/layout';

const { Content, Footer } = Layout;


const LandingPage = () => {
  const navigate = useNavigate();
  const { isLoggedIn, userRole } = useAuth();
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    checkLoginStatus();
  }, []);

  const checkLoginStatus = async () => {
    try {
     const role=localStorage.getItem('role')
      if (role) {
        navigate('/home');
        setLoading(true);
      } else {
        setLoading(false);
      }
    } catch (error) {
        console.error('Error checking login status', error);
        setLoading(false);
      }
  };

  if (loading) {
    return (
      <Layout style={{ height: '100vh' }}>
        <Content style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
          <Spin size="large" tip="Loading..." />
        </Content>
      </Layout>
    );
  }

  return (
    <Layout className='container'>
      <Content className='content'>
        {isLoggedIn ? (
          <>
            <Typography.Title level={2}>
              {userRole === 'user' ? '欢迎管理员' : '欢迎小二用户'}
            </Typography.Title>
            <Button type="primary" size="large" onClick={() => navigate('/home')}>
              {userRole === 'admin' ? '超级管理员' : '小二店员'}
            </Button>
          </>
        ) : (
          <><div className='title'>
            <Typography.Title level={2}>欢迎使用小二管理系统</Typography.Title>
            <p textAlign="center">请点击登录或注册以进入系统</p></div>
            <Space>
            <Button type="primary" size="large" onClick={() => navigate('/login')}>
              登录
            </Button>
            <Button size="large" onClick={() => navigate('/register')}>
              注册
            </Button>
            </Space>
          </>
        )}
      </Content>
      <Footer
        style={{
          textAlign: 'center',
        }}
      >
        Ant Design ©{new Date().getFullYear()} Created by Ant UED
      </Footer>
    </Layout>
  );
};

export default LandingPage;